package com.lhf.userservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lhf.userservice.dao.FvsSysPerDao;
import com.lhf.userservice.entity.FvsSysPer;
import com.lhf.userservice.service.FvsSysPerService;
import com.lhf.userservice.vo.FvsSysPerVO;
import com.lhf.userservice.vo.FvsSysRouterVO;
import com.lhf.userservice.vo.PerCascaderVo;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 权限(FvsSysPer)表服务实现类
 *
 * @author liuhf
 * @since 2021-03-29 16:02:05
 */
@Service("fvsSysPerService")
public class FvsSysPerServiceImpl extends ServiceImpl<FvsSysPerDao, FvsSysPer> implements FvsSysPerService {


    @Resource
    private FvsSysPerDao fvsSysPerDao;

    /**
     * 查询权限列表
     *
     * @param page
     * @param fvsSysPer
     * @return
     */
    @Override
    public Page<FvsSysPerVO> selectAll(Page<FvsSysPer> page, FvsSysPer fvsSysPer) {
        fvsSysPer.setParent(0L);
        return this.fvsSysPerDao.selectAll(page, fvsSysPer);
    }

    /**
     * 查询角色所有的权限
     *
     * @param rid
     * @return
     */
    @Override
    public List<FvsSysPerVO> findPerByRid(Long rid) {
        return this.fvsSysPerDao.findPerByRid(rid);
    }

    @Override
    public List<FvsSysPerVO> findPerByUid(Long uid, Long parentId) {
        List<FvsSysPerVO> per = this.fvsSysPerDao.findPerByUid(uid, parentId);

        for (FvsSysPerVO vo : per) {
            vo.setChildren(this.findPerByUid(uid, vo.getPid()));
        }
        return per;
    }

    @Override
    public Map<String, List> findPerAndRoute(Long uid, Long parentId) {
        Map<String, List> map = new HashMap<>();
        List<FvsSysPerVO> per = this.findPerByUid(uid, parentId);
        map.put("per", per);
        List<FvsSysRouterVO> routes = this.routeHandler(per).stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        map.put("route", routes);
        return map;
    }

    private List<FvsSysRouterVO> routeHandler(List<FvsSysPerVO> per) {
        List<FvsSysRouterVO> routes = new LinkedList<>();
        for (FvsSysPerVO vo : per) {
            routes.addAll(this.routeHandler(vo.getChildren()));
            routes.add(vo.getRoute());
        }
        return routes;
    }


    /**
     * 查询权限级联选择器
     *
     * @param parent
     * @return
     */
    @Override
    public List<PerCascaderVo> findPerCascaderByParent(Long parent) {
        return this.fvsSysPerDao.findPerCascaderByParent(parent);
    }

}
